<?php
/**
 * Created by PhpStorm.
 * User: HLG
 * Date: 2019/10/14
 * Time: 16:47
 */
namespace app\api\model;
use app\api\model\Balance;
use app\api\model\BalanceLog;
use app\api\model\Payment;
use app\api\model\Recharge;
use app\api\model\Pbank;
use app\api\model\Xtmessage;
use app\api\model\Umessage;
use app\api\model\Withdrawal;
use app\api\model\Mining;
use app\api\model\Classification;
use app\api\model\Grade;
use app\api\controller\Send;
use Qcloud\Cos\Md5Listener;
use think\Model;
use think\db;
class User extends BaseModel
{
    protected $table = 'content_user';

    /**
     * 用户注册
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function register()
    {
        $data = input('post.');
        $validate = new \app\api\validate\User();
        if(!$validate->scene('register')->check($data)){
            AjaxReturn(0,$validate->getError());
        }
        if($data['password']!=$data['password2']){
            AjaxReturn(0,'两次密码不一致');
        }

        //检测验证码
        $send = new Send();
        $checkCode = $send->checkCode($data['code'],$data['phone']);
        if($checkCode){
            //判断用户是否存在
            $user = $this->getUser(['phone'=>$data['phone']]);
            if($user){
                AjaxReturn(0,'用户已存在');
            }
            $this->startTrans();
            if(!empty($data['icode'])){ //添加邀请
                $userInfo=$this->getUser(['invitation_code'=>$data['icode']])->find();
                if($userInfo){
                    $data['pid']=$userInfo['id'];
                }
            }
            //添加用户信息
            $data['password'] = md5($data['password']);
            $data['create_time'] = time();
            $data['invitation_code'] = $this->recommand();
            $insertUser = $this->allowField(['phone','password','create_time','invitation_code','pid'])->save($data);
            if($insertUser){
                $newUser=$this->where(['phone'=>$data['phone']])->find();
                if(!empty($data['icode'])){
                    $save['path']=$userInfo['path'].','.$newUser['id'];
                    $save['id']=$userInfo['id'];
                    $save['resage_nu']=$userInfo['resage_nu']+1;
                    $updateUser = $this->allowField(['path'])->save($save);
                    if($updateUser===false){
                        $this->rollback();
                        AjaxReturn(0,'注册失败');
                    }
                }
                $insertMine = $this->insertMine($newUser['id']); //增加试用矿
                if($insertMine){
                    $this->commit();
                    AjaxReturn(1,'注册成功');
                }
                $this->rollback();
                AjaxReturn(0,'注册失败');
            }else{
                $this->rollback();
                AjaxReturn(0,'注册失败');
            }
        }
    }
    /**
     * 生成随机数
     * @param $len
     * @return string
     */
    function genRequestSn($unique=0){
        $orderNo = date('YmdHis').substr(microtime(), 2, 5) . mt_rand(10000,99999);
        if(!empty($unique)) $orderNo = $orderNo.$unique;
        return $orderNo;
    }
    /**
     * 增加使用矿
     */
    public  function  insertMine($uid){
        $info=db::name('content_advs_category')->find(1);
        $arr=[
            'price'=>$info['price'],
            'name'=>$info['title'],
            'day_num'=>$info['day_num'],
            'song'=>$info['song'],
            'xiaohao'=>$info['xiao'],
            'user_id'=>$uid,
            'order_sn'=>$this->genRequestSn(),
            'end_days'=>$info['day'],
            'pay_time'=>time(),
            'create_time'=>time()
        ];
        $mine_id=Db::name('content_classification_order')->insertGetId($arr);
        $data=[
            'user_id'=>$uid,
            'mine_id'=>$mine_id,
            'type'=>1,
            'run_time'=>$info['run_time']
        ];
        $mining=Mining::insert($data);
        if($mine_id && $mining){
            return true;
        }
        return false;
    }
    /**
     * 用户登录
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $data = input('post.');
        $validate = new \app\api\validate\User();
        if(!$validate->scene('login')->check($data)){
            AjaxReturn(0,$validate->getError());
        }
        //$data['pay_password'] = md5($data['pay_password']);
        $data['password'] = md5($data['password']);
        //验证登录数据
        $check = $this->where($data)->find();
        if($check){
            //添加资金账户
            $balance= new Balance();
            $addBalance=$balance->addBalance($check['id']);
            if(!$addBalance){
                AjaxReturn(0,'登录失败');
            }
            $token = md5(time().$check['id']);
            //修改登录凭证
            $updateToken = $this->updateInfo(['id'=>$check['id']],['token'=>$token]);
            if($updateToken){
                $arr = [
                    'uid'=>$check['id'],
                    'login_time'=>time(),
                    'status'=>0
                ];
                db('login_time')->insert($arr);
                AjaxReturn(1,'登录成功',$token);
            }else{
                AjaxReturn(0,'登录失败');
            }
        }else{
            AjaxReturn(0,'手机号或密码不正确');
        }
    }

    /**
     * 重置密码
     */
    public function resetPassword()
    {
        $data = input('post.');
        $validate = new \app\api\validate\User();
        if(!$validate->scene('register')->check($data)){
            AjaxReturn(0,$validate->getError());
        }
        if($data['password']!=$data['password2']){
            AjaxReturn(0,'两次密码不一致');
        }
        $password = md5($data['password']);
        //修改密码
        $send = new Send();
        $checkCode = $send->checkCode($data['code'],$data['phone']);
        if($checkCode){
            $updatePassword = $this->updateInfo(['phone'=>$data['phone']],['password'=>$password]);
            if($updatePassword!==false){
                AjaxReturn(1,'修改成功');
            }else{
                AjaxReturn(0,'修改失败');
            }
        }
    }
    /**
     * 修改密码
     */
    public function editPassword($uid,$data){
        $userInfo=$this->getUser(['id'=>$uid]);
        if($userInfo['password']==md5($data['oldpassword'])){
            if($data['password']==$data['password2']){
                AjaxReturn(1,'修改成功');
            }else{
                AjaxReturn(0,'修改失败');
            }
        }else{
            AjaxReturn(0,'修改失败');
        }
    }
    /**
     * 修改用户信息
     */
    public function editUser($uid,$data){
        $save['uname']=$data['uname']; //用户名
        $save['sex']=$data['sex']; //性别 1男 2女
        $save['hear']=$data['hear']; //头像
        $updatePassword = $this->updateInfo(['id'=>$uid],$save);
        if($updatePassword!==false){
            AjaxReturn(1,'修改成功');
        }else{
            AjaxReturn(0,'修改失败');
        }
    }
    /**
     * 查询某个用户信息
     * @param array $where
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUser($where=[])
    {
        $data = $this->where($where)->find();
        $data['isok']=0;

        $authenModel = new Authentic();
        //判断是否存在数据
        $userAuthentic = $authenModel->getInfo(['user_id'=>$data['id']]);
        if($userAuthentic && $userAuthentic['state']==1) {
            $data['isok']=1;
        }
        return $data;
    }
    /**
     * 查询某个实名认证信息
     * @param array $where
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function  authenticationInfo($uid){
        $authenModel = new Authentic();
        //判断是否存在数据
        $data=$authenModel->where(['user_id'=>$uid])->find();
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 实名认证
     * @param $user_id
     */
    public function authentication($user_id)
    {
        $data = input('post.');
        $validate = new \app\api\validate\User();
        if(!$validate->scene('authentic')->check($data)){
            AjaxReturn(0,$validate->getError());
        }
        //添加实名信息
        $data['user_id'] = $user_id;
        $data['create_time'] = time();
        $data['true_name'] = $data['true_name'];
        $data['mobile'] = $data['mobile'];
        $data['idcard'] = $data['idcard']; //身份证号
        $data['positive'] = $data['positive']; //身份证正面
        $data['back'] = $data['back'];//身份证反面
        $authenModel = new Authentic();
        //判断是否存在数据
        $userAuthentic = $authenModel->getInfo(['user_id'=>$user_id]);
        $this->startTrans();
        if($userAuthentic){
            //判断是否认证成功
            if($userAuthentic['state'] == 1){
                AjaxReturn(0,'请勿重复认证');
            }else{
                $data['state']=0;
                $addRes = $authenModel->updateInfo(['user_id'=>$user_id],$data);
            }
        }else{
            $addRes = $authenModel->insertInfo($data);
        }
        if($addRes){
            $this->commit();
            AjaxReturn(1,'认证成功');
        }
        AjaxReturn(0,'认证失败');

    }

    /**
     * 随机生成邀请码/ID
     *
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function recommand()
    {
        $length = 6;
        // 密码字符集，可任意添加你需要的字符
        $chars = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars, $length);
        $invitation = '';
        for ($i = 0; $i < $length; $i++) {
            // 将 $length 个数组元素连接成字符串
            $invitation .= $chars[$keys[$i]];
        }
        $check_code = $this->where('invitation_code',$invitation)->find();
        if($check_code){
            $this->recommand();
        }else{
            return $invitation;
        }
    }
    /**
     * 上传支付凭证
     */
    public function upload(){
        return upload();
    }
    /**
     * 添加收款凭证
     */
    public function addPayMent($uid,$data){
        $arr['payment']=$data['payment'];//1微信 2支付宝 3银行卡
        $arr['uid']=$uid;
        if($data['payment']==1 || $data['payment']==2){
            $arr['pay_img']=$data['pay_img'];

        }
        if($data['payment']==3){
            $arr['opening_bank']=$data['opening_bank'];
            $arr['opening_name']=$data['opening_name'];
            $arr['card_num']=$data['card_num'];
        }
        $arr['create_time']=time();
        if($data['payment']==3){
            $addRes=payMent::insert($arr);
        }else{
            if($info=payMent::where(['uid'=>$uid,'payment'=>$data['payment']])->find()){
                $addRes=payMent::where(['uid'=>$uid,'payment'=>$data['payment']])->update($arr);
            }else{
                $addRes=payMent::insert($arr);
            }
        }

        if($addRes){
            AjaxReturn(1,'成功');
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 获取收款凭证
     */
    public function  getPayMent($uid,$patment){
        if($patment==3){
            $data=payMent::where(['uid'=>$uid,'payment'=>$patment,'status'=>1])->select();
        }else{
            $data=payMent::where(['uid'=>$uid,'payment'=>$patment,'status'=>1])->find();

        }
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 获取收款卡号
     */
    public function  getPayList(){
        $data=Pbank::select();
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 充值
     */
    public function addPay($uid,$data){
        $arr['uid']=$uid;
        $arr['pt_id']=$data['pt_id'];//收款卡id
        $arr['ordernum']=md5(time() . mt_rand(1,1000000));
        $arr['price']=$data['price'];
        $arr['num']=$data['price'];
        $arr['pay_img']=$data['pay_img'];
        if(empty($data['pay_img'])){
            AjaxReturn(0,'请上传支付凭证');
        }
        $arr['create_time']=time();
        $addRes=Recharge::insert($arr);
        if($addRes){
            AjaxReturn(1,'成功');
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 提现
     */
    public function cash($uid,$data){
        $balance=balance::where(['uid'=>$uid])->find();
        $config=db::name('content_advs_category_config')->find();
        if($balance['mineral']<$data['price']){
            AjaxReturn(0,'余额不足');
        }
        if($data['price']<$config['manti']){
            AjaxReturn(0,'超出提现限制');
        }
        $arr['uid']=$uid;
        //$arr['type']=$data['type'];//1微信 2支付宝 3银行卡
        $arr['sid']=$data['sid'];//收款id
        $arr['price']=$data['price'];
        $arr['actual_price']=$data['price']*(100-$config['shouxufei'])/100;
        $arr['create_time']=time();

        $addRes=withdrawal::insert($arr);
        if($addRes){
            AjaxReturn(1,'成功');
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 获取系统消息
     */
    public function getMessage($uid){
        $where['uid']=$uid;
        $where['status']=1;
        $data=Xtmessage::whereor($where)->order('create_time desc')->select();
        foreach ($data as $key=>$value){
            $isok=Umessage::where(['uid'=>$uid,'mid'=>$value['id']])->find();
            $data[$key]['is_read']=$isok?1:0;
            $data[$key]['create_time']=date('Y-m-d H:i:s',$value['create_time']);
        }
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 消息详情
     */
    public function messageInfo($mid){
        $data=Xtmessage::find($mid);
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 已读系统消息
     */
    public function messageSave($uid,$mid){
        $user=Umessage::where(['uid'=>$uid])->find();
        if($user){
            AjaxReturn(1,'成功');
        }
        $arr['uid']=$uid;
        $arr['mid']=$mid;
        $arr['create_time']=time();
        $addRes=Umessage::insert($arr);
        if($addRes){
            AjaxReturn(1,'成功');
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 获取收益
     */
    public function getPrice($uid){
        $data=BalanceLog::where(['type'=>8,'uid'=>$uid])->paginate(10);
        foreach ($data as $key=>$v){
            $data[$key]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
        }
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 获取系统配置config
     */
    public function getConfig(){
        $data=db::name('content_advs_category_config')->find();
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 点击采矿
     */
    public function clickMining($uid,$mine_id){
        $order=Classification::find($mine_id);
        $start=date('Y-m-d H:i:s',$order['create_time']);
        $end=strtotime($start.' +'.$order['end_days'].' day');
        if(time() > $end ){
            AjaxReturn(-1,'无效的矿山');
        }
        $data=Mining::where(['user_id'=>$uid,'mine_id'=>$mine_id])->find();
        if($data['end_time']>time()){
            AjaxReturn(-1,'无法点击,暂未结束');
        }
        $balance=balance::where(['uid'=>$uid])->field('sum(absenteeism+ontrial_absenteeism) as total,absenteeism,ontrial_absenteeism')->find();
        if($balance['total']<$order['xiaohao']){
            AjaxReturn(-1,'旷工数量不足，请充值');
        }
        db::startTrans();
        $end_time=strtotime('+'.$data['run_time'].' hour');
        $addRes=Mining::where(['user_id'=>$uid,'mine_id'=>$mine_id])->update(['start_time'=>time(),'end_time'=>$end_time,'state'=>1]);
        if($addRes) {
            $balanceModel = new Balance();
            $number=$balance['ontrial_absenteeism']-$order['xiaohao'];
            if($number<0){
                $balanceRes = $balanceModel->changeBalance($uid,'ontrial_absenteeism',$balance['ontrial_absenteeism'],2,10,'消耗试用旷工');
                if($balanceRes){
                    $onnumber= abs($number);
                    $balanceRes= $balanceModel->changeBalance($uid,'absenteeism',$onnumber,2,10,'消耗旷工');
                    if($balanceRes){
                        db::commit();
                        AjaxReturn(1,'成功',['end_time'=>date('Y-m-d H:i:s',$end_time)]);
                    }
                }
            }else{
                $balanceRes = $balanceModel->changeBalance($uid,'ontrial_absenteeism',$order['xiaohao'],2,10,'消耗试用旷工');
                if($balanceRes){
                    db::commit();
                    AjaxReturn(1,'成功',['end_time'=>date('Y-m-d H:i:s',$end_time)]);
                }
            }

            db::rollback();
            AjaxReturn(0,'失败');
        }
        db::rollback();
        AjaxReturn(0,'失败');
    }
    /**
     * 采矿结束
     */
    public function endMining($user_id,$mine_id){
        $data=Mining::where(['user_id'=>$user_id,'mine_id'=>$mine_id])->find();
        if($data['end_time']>time()){
            AjaxReturn(-1,'暂未结束，无法点击');
        }
        if($data['state']==0){
            AjaxReturn(-1,'请先开始');
        }
        $state=0;
        // 转换为 YYYY-MM-DD 格式
        $a_date = date('Y-m-d',$data['start_time']);
        // 获取今天的 YYYY-MM-DD 格式
        $b_date = date('Y-m-d');
        // 使用IF当作字符串判断是否相等
        if($a_date==$b_date){
            $state=2;
        }
        $this->startTrans();
        $order=Classification::find($data['mine_id']);
        $balanceModel = new Balance();
        $balanceRes = $balanceModel->changeBalance($user_id,'mineral',$order['day_num'],1,8,'开采钻石');
        $addRes=Mining::where(['user_id'=>$user_id,'mine_id'=>$mine_id])->update(['state'=>$state]);
        $user=$this->find($user_id);
        if(!empty($user['pid'])){
            $parent=$this->find($user['pid']);
            $grade= Grade::where(['lv'=>$parent['lv']])->find();
            if($grade){
                $yesterday_start=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                $yesterday_end=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;

                $price=$grade['return_commission']/100*$order['day_num'];
                $where['create_time']=array('<=',$yesterday_end);
                $where['create_time']=array('>=',$yesterday_start);
                $where['type']=9;
                $where['uid']=$parent['id'];
                $banlanceInfo=Balance::where($where)->field('sum(number) as total')->find();
                $lc=$banlanceInfo['total']*$grade['return_commission'];
                if($lc<$price){
                    $price=$lc;
                }
                $balanceModel->changeBalance($parent['id'],'mineral',$price,1,9,'开采返佣');
                BalanceLog::where(['uid'=>$parent['id']])->update(['fuid'=>$user_id]);
            }
        }
        if($balanceRes && $addRes){
            $this->commit();
            $status = ['code'=>1,'msg'=>'采矿成功'];
        }else{
            $this->rollback();
            $status = ['code'=>0,'msg'=>'采矿失败'];
        }
        return $status;
    }
    /**
     * 生成邀请二维码
     */
    public function QRcode($uid){

        $user=$this->getUser(['id'=>$uid]);
        $savePath = env('root_path').DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'qrcode/';
        $qrData = 'http://voice.lookupok.com/api/index/index?icode='.$user['invitation_code'];
        $qrLevel = 'H';
        $qrSize = '8';
        $savePrefix = 'NickBai';
        $filename = QRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix);
        return '/qrcode/'.$filename;
    }
    //获取收益详情
    public function  getPriceInfo($id){
        $data= BalanceLog::find($id);
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 获取我的团队
     */
    public  function  getMyDeal($uid){
        $info=$this->getUser(['id'=>$uid]);
        $uids=explode(',',$info['path']);
        $where['uid']=$uids;
        $where['type']=9;
        $arr['myTotal']=BalanceLog::where(['type'=>9,'uid'=>$uid])->field('sum(number) as number')->find()['number']; //总收益
        $arr['timTotal']=BalanceLog::where($where)->field('sum(number) as number')->find()['number']; //团队收益
        $arr['number']=count($uids); //队员人数
        $arr['list']=$this->where(['id'=>$uids])->field('id,phone,uname')->select();

        $authenModel = new Authentic();
        foreach ($arr['list'] as $key=>$value){
            $arr['list'][$key]['isok']=0;
            //判断是否存在数据
            $userAuthentic = $authenModel->getInfo(['user_id'=>$value['id']]);
            if($userAuthentic && $userAuthentic['state']==1) {
                $arr['list'][$key]['isok']=1;
            }
            $arr['list'][$key]['total']=BalanceLog::where(['fuid'=>$value['id']])->field('sum(number) as number')->find()['number'];
        }
        if($arr){
            AjaxReturn(1,'成功',$arr);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 删除银行卡
     */
    public function deleteBank($id){
        $data= payMent::where(['id'=>$id])->delete();
        if($data){
            AjaxReturn(1,'成功',$data);
        }
        AjaxReturn(0,'失败');
    }
    /**
     * 更新每日挖矿次数
     */
    public function   editTime(){
        $now=strtotime(date('Y-m-d'));
        $arr['start_time']=array('lt',$now);
        $arr['state']=2;
        Mining::where($arr)->update(['state'=>0]);
    }
}
